<template>
	<div v-bind="$attrs" class="base-table">
		<slot name="title" />
		<slot />
		<el-table
			v-tableMove
			id="checkTable"
			:row-style="rowStyle"
			:max-height="tableHeight"
			:height="tableHT"
			:data="data"
			:stripe="stripe"
			border
			:ref="$attrs.ref || refs"
			v-bind="tableAttrs"
			style="width: 100%"
			@row-click="tableDetails"
			@row-dblclick="tableDetailsdb"
			:row-class-name="tableRowClassNameOut || tableRowClassName"
			@selection-change="handleSelectionChange"
			@select-all="onSelectAll"
			:row-key="getRowKeys"
			v-loading="loading"
			element-loading-text="网络开小差，正在努力加载..."
			element-loading-spinner="el-icon-loading"
			:show-summary="isShow"
			:summary-method="getSummaries"
			:span-method="arraySpanMethod || tableRowSpan"
		>
			<el-table-column
				type="selection"
				width="55"
				:selectable="modelType == 1 ? selectable : checkBox"
				:disabled="true"
				reserve-selection
				v-if="selectShow"
			/>
			<template v-for="(col, index) in columnAttrs">
				<el-table-column v-if="col.child" v-bind="col" show-overflow-tooltip align="center" :key="index">
					<el-table-column
						v-bind="colB"
						v-for="(colB, indexB) in col.child"
						:key="indexB"
						show-overflow-tooltip
					></el-table-column>
				</el-table-column>
        <el-table-column v-else-if="!col.render" v-bind="col" :key="index" show-overflow-tooltip >
          <template slot-scope="scope">
            <div v-if="col.isShort">
              {{ scope.row[col.prop] | customerShortName }}
            </div>
            <div v-else>
              {{ scope.row[col.prop] }}
            </div>
          </template>
        </el-table-column>

				<!-- <el-table-column v-else v-bind="col" v-for="(col, index) in columnAttrs" :key="index">render渲染重复数据 -->

				<el-table-column v-else v-bind="col" :key="index" show-overflow-tooltip>
					<template slot-scope="scope">
						<expandDom :row="scope.row" :col="col" :render="col.render" :col-index="index" />
					</template>
				</el-table-column>
			</template>
		</el-table>
		<!-- 		<el-pagination v-if="paginationAttrs.isPagination" v-bind="paginationAttrs" class="pagination-container" @size-change="handleSizeChange"
    @current-change="handleCurrentChange" />-->
		<!-- <el-pagination v-bind="paginationAttrs" class="pagination-container" @size-change="handleSizeChange" @current-change="handleCurrentChange" /> -->
		<div class="page" v-if="paginationAttrs.isPagination">
			<el-pagination
				background
				layout="total, sizes, prev, pager, next, jumper"
				:total="paginationAttrs.totalNum"
				:current-page="paginationAttrs.startpage"
				:page-size="paginationAttrs.pagesize"
				class="pagination-container"
				:page-sizes="pageSizes ? pageSizes : [10, 15, 30, 50]"
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
			></el-pagination>
		</div>
	</div>
</template>
<script>
import { defaultTableAttrs, defaultColumn, defaultPagination } from "./tableConfig"

export default {
	multipleSelection: [],
	name: "BaseTable",
	components: {
		expandDom: {
			functional: true,
			props: {
				row: Object,
				col: Object,
				render: Function,
				colIndex: [Number, String],
			},
			render(h, ctx) {
				const randomIndex = Math.random().toString(35).replace(".", "")
				const params = {
					row: {
						...ctx.props.row,
					},
					colIndex: ctx.props.colIndex || randomIndex,
				}
				if (ctx.props.col) {
					params.col = ctx.props.col
				}
				return ctx.props.render && ctx.props.render(h, params)
			},
		},
	},
	props: {
		// row-class-name函数
		tableRowClassNameOut: {
			type: Function,
		},
		//表格行样式
		rowStyle: {
			type: Function,
		},
		//是否为显示多选框
		selectShow: {
			type: Boolean,
			default: true,
		},
		refs: {
			type: String,
			default: "instance",
		},
		loading: {
			type: Boolean,
			default: false,
		},
		data: {
			type: Array,
			default() {
				return []
			},
		},
		columns: {
			type: Array,
			default() {
				return []
			},
		},
		pagination: {
			type: [Object, Boolean],
			default() {
				return Object
			},
		},
		// 判断checkbox是否可选
		dataType: {
			type: Boolean,
			default: true,
		},
		tableHeight: {
			type: Number,
			// default: window.innerHeight - 350
		},
		tableHT: {
			type: [Number, String],
		},
		checkBoxDisabled: {
			type: Function,
		},
		isSelectAll: {
			type: Boolean,
			default: true,
		},
		modelType: {
			type: Number,
		},
		selectionList: {
			type: Array,
		},
		htmlName: {
			type: String,
		},
		selectionValueList: {
			type: Array,
		},
		isSelect: {
			type: Boolean,
		},
		valueType: {
			type: Number,
		},
		checkList: {
			type: Array,
		},
		valueList: {
			type: Array,
		},
		selectChange: {
			type: Function,
		},
		// 自定义条数
		pageSizes: {
			type: Array,
		},
		isShow: {
			type: Boolean,
		},
		// 是否展示斑马纹 默认展示
		stripe: {
			type: Boolean,
			default: true,
		},
		// arraySpanMethod
		arraySpanMethod: {
			type: Function,
		},
	},
	data() {
		return {
			table: null, //table的元素
			scrollLeft: 0, //记录拉动位置
			isDrag: false, //是否为拖动状态
			// tableHeight: window.innerHeight - 350,
			tableAttrs: {},
			columnAttrs: [],
			paginationAttrs: {
				totalNum: 0,
				startpage: 0,
				pagesize: 0,
			},
			chooseId: "",
		}
	},
	watch: {
		pagination: {
			handler(val) {
				this.getPagination()
			},
			deep: true,
		},
		columns: {
			deep: true,
			async handler(value) {
				this.columnAttrs = value.map(column => {
					const obj = Object.assign({}, defaultColumn, column)
					return obj
				})
			},
		},
		data: {
			deep: true,
			async handler(value) {
				if (this.checkList) {
					value.map(item => {
						this.checkList.map(childItem => {
							if (item.id == childItem.id) {
								this.$refs.instance.toggleRowSelection(item, true)
							}
						})
					})
				}
			},
		},
	},
	created() {
		this.$nextTick(() => {
			this.init()
		})
	},
	mounted() {
		this.$nextTick(() => {
			this.data.map(item => {
				// console.log(this.selectionValueList)
				// if (this.selectionValueList.length != 0 && this.selectionValueList != undefined) {
				//     this.selectionValueList.map((grandItem)=>{
				//         if (item.id == grandItem.id) {
				//             this.$refs.instance.toggleRowSelection(item, true)
				//         }
				//     })
				// }
				if (this.selectionList) {
					this.selectionList.map(childItem => {
						if (item.id == childItem.tugboatId) {
							item.tugboatStatus = childItem.tugboatStatus ? childItem.tugboatStatus : ""
							item.workStartDate = childItem.workStartDate ? childItem.workStartDate : ""
							this.$refs.instance.toggleRowSelection(item, true)
						}
					})
				}
				if (this.valueList) {
					this.valueList.map(childItem => {
						if (item.storehouseId == childItem) {
							this.$refs.instance.toggleRowSelection(item, true)
						}
					})
				}
			})
		})
	},
	methods: {
		tableRowSpan() {},
		toggleSelection(rows) {
			if (rows) {
				rows.forEach(row => {
					this.$refs.instance.toggleRowSelection(row)
				})
			} else {
				this.$refs["instance"].clearSelection()
			}
		},
		getRowKeys(row) {
			return row.index
		},

		// 根据票货id实现部分checkbox不可选
		checkBox(row, index) {
			if (this.chooseId != "") {
				if (this.chooseId == row.ticketId) {
					return 1
				} else {
					return 0
				}
			} else if (!this.dataType) {
				if (row.workTypeName === "零星线") {
					return 1
				} else {
					return 0
				}
			} else if (this.isSelect) {
				if (row.isUsed) {
					return 1
				} else if (!row.isUsed) {
					return 0
				}
			} else {
				return 1
			}
		},
		/**
		 * @Author: gonghairun
		 * @description: 实现部分checkbox不可选
		 * @param {*} row
		 * @param {*} index
		 * @return {*}
		 */
		selectable(row, index) {
			return this.checkBoxDisabled(row, index)
		},
		/**
		 * @Author: gonghairun
		 * @description: 全选
		 * @param {*}
		 * @return {*}
		 */
		onSelectAll() {
			if (this.isSelectAll === false) {
				this.$refs["instance"].clearSelection() //这个是清除所有选择项，当选择全部时，清除所有选择项
			}
		},
		init() {
			// 获取element table上的属性
			const tableAttrs = {}
			Object.keys(defaultTableAttrs).forEach(key => {
				if (this.$attrs[key] !== undefined) {
					tableAttrs[key] = this.$attrs[key]
				}
			})
			this.tableAttrs = Object.assign({}, defaultTableAttrs, tableAttrs)

			// 获取element table col上的属性
			this.columnAttrs = this.columns.map(column => {
				const obj = Object.assign({}, defaultColumn, column)
				return obj
			})
			this.getPagination()
		},
		getPagination() {
			// 获取element 分页属性
			const pagination = this.pagination
			let paginationAttrs = {}
			if (pagination) {
				if (typeof pagination === "object") {
					paginationAttrs = {
						...defaultPagination,
						...pagination,
						isPagination: true,
					}
				} else {
					paginationAttrs = {
						...defaultPagination,
						isPagination: false,
					}
				}
			}
			Object.keys(paginationAttrs).forEach(key => {
				if (this.$attrs[key] !== undefined && key !== "pagination") {
					paginationAttrs[key] = this.$attrs[key]
				}
			})
			this.paginationAttrs = paginationAttrs
		},
		handleSizeChange(pageSize) {
			this.$emit("size-change", pageSize)
		},
		handleCurrentChange(page) {
			this.$emit("current-change", page)
		},
		tableRowClassName({ row, rowIndex }) {
			row.index = rowIndex
		},
		tableDetails(row, event, column) {
			//单击事件
			var index = row.index
			this.$emit("details", row)
		},
		tableDetailsdb(row, event, column) {
			//双击事件
			var index = row.index
			this.$emit("detailsdb", row)
		},
		//checkbox选择时id
		handleSelectionChange(val) {
			this.multipleSelection = val
			this.$emit("checkId", val)
			this.selectChange ? this.selectChange(val) : ""
			//需要禁用checkBox的情况
			if (val.length != 0) {
				if (val[0].tableFlag == 1) {
					this.chooseId = val[0].ticketId
				}
			} else {
				this.chooseId = ""
			}
		},
		//清空选中向
		clearSelection() {
			this.$refs.instance.clearSelection()
		},
		toggleRowSelection(row, flag) {
			this.$refs.instance.toggleRowSelection(row, flag)
		},
		getSummaries(param) {
			const { columns, data } = param
			const sums = []
			console.log(data)

			columns.forEach((column, index) => {
				if (index === 0) {
					sums[index] = "合计"
					return
				}
				if (column.property == "bczxdw") {
					sums[index] = this.extraData
				}
				if (this.isShow) {
					if (column.property == "numP" || column.property == "weightP") {
						const values = data.map(item => Number(item[column.property]))
						if (!values.every(value => isNaN(value))) {
							sums[index] = (values.reduce((prev, curr) => {
								const value = Number(curr)
								if (!isNaN(value)) {
									return prev + curr
								} else {
									return prev
								}
							}, 0)).toFixed(3)
							sums[index] += ""
						} else {
							sums[index] = ""
						}
					}
				}
			})
			return sums
		},
	},
	updated() {
		this.$nextTick(() => {
			this.$refs["instance"].doLayout()
		})
	},
	destroyed() {
		// let tableScroll = this.table.childNodes[2]
		// tableScroll.removeEventListener('scroll',this.tableScroll)
	},
}
</script>
<style lang="less" scoped>
#checkTable {
	-moz-user-select: none;
	-webkit-user-select: none;
	user-select: none;
}
.page {
	z-index: 666;
}
.base-table {
	/deep/ .el-table--border td {
		border-right: none;
	}
	/deep/ .el-table--border th {
		border-right: none;
	}
}
@import "../../assets/table";
</style>
